let request = require('../../utils/request.js')
Page({
  data: {
    showd: false,
    second: '获取验证码',
    cardId: '',
    postlist: {},
    mobile: '',
    code: '',
    username: ''
  },
  //获取验证码
  getcode() {
    let url = '/Index/smsSend';
    let data = {};
    data.num = this.data.mobile;
    let re = /^1[0-9]{10}$/;
    if (!re.test(this.data.mobile)) {
      my.showToast({
        content: "手机格式错误",
        type: "fail",
        duration: 1000
      });
      return false;
    }
    let success = ()=> {
      my.showToast({
        content: '发送成功',
        type: 'success',
        duration: 1500
      });
      this.setData({
        second: 60,
        codebtn: true
      })
      let countdown = setInterval(() =>{
        if (this.data.second == 0) {
          this.setData({
            second: '获取验证码',
            codebtn: false
          })
          clearInterval(countdown)
        } else {
          this.setData({
            second: this.data.second - 1
          })
        }
      }, 1000);
    }
    request.postdata(url, data, success, this);
  },
  username_input(e) {
    this.data.username = e.detail.value
    this.setData({
      username: e.detail.value
    });
  },
  mobile_input (e) {
    this.data.mobile = e.detail.value
    this.setData({
      mobile: e.detail.value
    });
  },
  code_input (e) {
    this.data.code = e.detail.value
    this.setData({
      code: e.detail.value
    });
  },
  //绑定手机
  binding() {
    let url = '/index/binding';
    this.data.postlist.username = this.data.username;
    this.data.postlist.cardId = this.data.cardId;
    this.data.postlist.mobile = this.data.mobile;
    this.data.postlist.code = this.data.code;
    let success = (res) => {
      my.setStorageSync({
        key: "token",
        data: res
      })
      my.redirectTo({
        url: 'index?cardId=' + this.data.cardId
      })
      my.showToast({
        content: '绑定成功',
        type: 'success',
        duration: 1500,
      });
    };
    request.postdata(url, this.data.postlist, success, this);
  },
  onLoad(data) {
    if(data){
      this.data.cardId = data.cardId
    }
    my.getNetworkType({
      success: (res) => {
        if (!res.networkAvailable || res.networkType == 'UNKNOWN') {
          my.showToast({
            content: '网络状态不佳，请检查网络',
            type: 'fail',
            duration: 2000
          })
        }
      }
    })
  }
})

